Unit-678 QB Solution

Manish Patel

Jan 8, 2024

1. Writing customer data to a file (cust_data() function):


def cust_data():
    with open("customer.txt", "a") as file:
        name = input("Enter your name: ")
        age = input("Enter your age: ")
        file.write(f"Name: {name}, Age: {age}\n")

# Call the function to gather customer data
cust_data()

2. Creating and reading the city.txt file:

# Writing to city.txt
with open("city.txt", "w") as file:
    file.write("New York\nLondon\nTokyo\n")

# Reading and printing the contents of city.txt
with open("city.txt", "r") as file:
    contents = file.read()
    print(contents)

3. Counting and displaying total lines (count_lines() function):

def count_lines(filename):
    with open(filename, "r") as file:
        lines = file.readlines()
        total_lines = len(lines)
        print(f"Total number of lines: {total_lines}")

# Call the function with the provided file
count_lines("friends.txt")

4. Displaying odd-numbered lines (display_oddLines() function):

def display_oddLines(filename):
    with open(filename, "r") as file:
        lines = file.readlines()
        odd_lines = [line.strip() for i, line in enumerate(lines, 1) if i % 2 != 0]
        for line in odd_lines:
            print(line)

# Call the function with the provided file
display_oddLines("friends.txt")

5. Write a Python program to read a text file and do following: 1. Print no. of words 2. Print no. statements

def count_words_and_statements(filename):
    with open(filename, 'r') as file:
        content = file.read()
        words = len(content.split())
        statements = content.count('.') + content.count('!') + content.count('?')
        print(f"Number of words: {words}")
        print(f"Number of statements: {statements}")

# Example usage:
count_words_and_statements('your_file.txt')

6. Write a python program that reads a text file and changes the file by capitalizing each character of file.

def capitalize_file(input_filename, output_filename):
    with open(input_filename, 'r') as infile:
        content = infile.read()

    capitalized_content = content.upper()

    with open(output_filename, 'w') as outfile:
        outfile.write(capitalized_content)

# Example usage:
capitalize_file('input.txt', 'output.txt')

7. Write a Python program to copy the contents of a file to another file.

def copy_file(input_filename, output_filename):
    with open(input_filename, 'r') as infile:
        content = infile.read()

    with open(output_filename, 'w') as outfile:
        outfile.write(content)

# Example usage:
copy_file('source.txt', 'destination.txt')

8. Write a python program to read line by line from a given files file1 & file2 and write into file3.

def merge_files(file1, file2, file3):
    with open(file1, 'r') as f1, open(file2, 'r') as f2, open(file3, 'w') as f3:
        for line in f1:
            f3.write(line)
        for line in f2:
            f3.write(line)

# Example usage:
merge_files('file1.txt', 'file2.txt', 'file3.txt')

9. Write python program to count the number of lines in a file.

def count_lines(filename):
    with open(filename, 'r') as file:
        lines = file.readlines()
        line_count = len(lines)
        print(f"Number of lines: {line_count}")

# Example usage:
count_lines('your_file.txt')

10. Write a python program to search for a string in text files.

def search_string(filename, search_str):
    with open(filename, 'r') as file:
        content = file.read()
        if search_str in content:
            print(f"String '{search_str}' found in the file.")
        else:
            print(f"String '{search_str}' not found in the file.")

# Example usage:
search_string('your_file.txt', 'search_text')

15. Write a “pager” program. Your solution should prompt for a filename, and display the text file 25 lines at a time, pausing each time to ask the user to enter the word “continue”, in order to show the next 25 lines or enter the word “stop” to close the file.

def pager(filename):
    with open(filename, 'r') as file:
        lines = file.readlines()
        total_lines = len(lines)
        start = 0
        end = min(25, total_lines)

        while start < total_lines:
            for i in range(start, end):
                print(lines[i], end='')

            user_input = input("Enter 'continue' to show the next 25 lines or 'stop' to close the file: ")

            if user_input.lower() == 'stop':
                break

            start += 25
            end = min(start + 25, total_lines)

# Example usage:
pager('your_file.txt')

Using a file which consists of multiple statements, find all the words from the file that can be made from all the characters of given user’s string.

Note: If user enters same characters multiple times in a string, then word from file will only be eligible for output if it contains that character for same or more number of times in it. (if file have apple, greenapple and user’s string is ‘aepe’ then output will only be greenapple. apple is not eligible as it contains e for 1 time only.

def find_words_in_file(user_string, filename):
    user_char_count = {}
    for char in user_string:
        user_char_count[char] = user_char_count.get(char, 0) + 1

    eligible_words = []

    with open(filename, 'r') as file:
        for line in file:
            words = line.strip().split()
            for word in words:
                word_char_count = {}
                for char in word:
                    word_char_count[char] = word_char_count.get(char, 0) + 1

                is_eligible = True
                for char, count in user_char_count.items():
                    if char not in word_char_count or word_char_count[char] < count:
                        is_eligible = False
                        break

                if is_eligible:
                    eligible_words.append(word)

    return eligible_words

# Example usage:
user_input = input("Enter your string: ")
result = find_words_in_file(user_input, 'your_file.txt')
print("Eligible words:", result)

Write a Python program to reverse the content of a one file and store it in second file and also convert content of second file into uppercase and store it in third file and also count number of Vowels in third file and also print only 2nd line from the content of third file.

Examples: If data file one contains the following data: Friends are crazy, Friends are naughty ! Friends are honest, Friends are best !

Output 1:
! tseb  era sdneirF ,tsenoh era sdneirF
! ythguan era sdneirF ,yzarc era sdneirF

Output 2:
! TSEB  ERA SDNEIRF ,TSENOH ERA SDNEIRF
! YTHGUAN ERA SDNEIRF ,YZARC ERA SDNEIRF

Output 3:
Vowels = 22

Output 4:
! YTHGUAN ERA SDNEIRF ,YZARC ERA SDNEIRF

def reverse_file(input_file, output_file):
    with open(input_file, 'r') as f:
        content = f.read()
    
    reversed_content = content[::-1]
    
    with open(output_file, 'w') as f:
        f.write(reversed_content)

def convert_to_uppercase(input_file, output_file):
    with open(input_file, 'r') as f:
        content = f.read()
    
    uppercase_content = content.upper()
    
    with open(output_file, 'w') as f:
        f.write(uppercase_content)

def count_vowels(input_file):
    with open(input_file, 'r') as f:
        content = f.read()
    
    vowels = 'aeiouAEIOU'
    vowel_count = sum(1 for char in content if char in vowels)
    
    print(f'Vowels = {vowel_count}')

def print_second_line(input_file):
    with open(input_file, 'r') as f:
        lines = f.readlines()
    
    if len(lines) >= 2:
        second_line = lines[1].strip()
        print(second_line)

# Example usage:
file_one = 'file_one.txt'
file_two = 'file_two.txt'
file_three = 'file_three.txt'

reverse_file(file_one, file_two)
convert_to_uppercase(file_two, file_three)
count_vowels(file_three)
print_second_line(file_three)

Write a python program to extract a list of all four-letter words that start and end with the same letter from a given text file.

def extract_four_letter_words(filename):
    with open(filename, 'r') as file:
        words = file.read().split()

    result_words = [word for word in words if len(word) == 4 and word[0] == word[-1]]
    return result_words

# Example usage:
filename = 'text_file.txt'
result = extract_four_letter_words(filename)
print(result)

Write a python program to read a text file “Story.txt” and print only word starting with ‘I’ in reverse order.

Example: If value in text file is : ‘INDIA IS MY COUNTRY’
Output will be: ‘AIDNI SI MY COUNTRY’"
def print_i_words_reverse(filename):
    with open(filename, 'r') as file:
        words = file.read().split()

    i_words = [word[::-1] for word in words if word.startswith('I')]
    print(' '.join(i_words))

# Example usage:
filename = 'Story.txt'
print_i_words_reverse(filename)

Write a Python program to count words, characters and spaces from text file.

Input:

Python is a Easy Subject
OOPs is One of the most
interesting Topic

Output:

No of space: 10
No of word: 13
No of character: 64
"

def count_stats(filename):
    with open(filename, 'r') as file:
        content = file.read()

    word_count = len(content.split())
    char_count = len(content)
    space_count = content.count(' ')

    print(f'No of space: {space_count}')
    print(f'No of word: {word_count}')
    print(f'No of character: {char_count}')

# Example usage:
filename = 'text_file.txt'
count_stats(filename)

File Filtering. write all lines of a file1, except those that start with a hash sign ( # ), the comment character for Python to file2. And display data of file2.

Text file1 content:

Friends are crazy, Friends are naughty ! 
#Friends are honest, Friends are best ! 
Friends are like keygen, #friends are like license key ! 
We are nothing without friends, Life is not possible without friends !

Text file2 shoud be:

Friends are crazy, Friends are naughty !  
Friends are like keygen, 
We are nothing without friends, Life is not possible without friends !"

def filter_comments(input_filename, output_filename):
    with open(input_filename, 'r') as input_file:
        lines = input_file.readlines()

    filtered_lines = [line for line in lines if not line.startswith('#')]

    with open(output_filename, 'w') as output_file:
        output_file.writelines(filtered_lines)

# Example usage:
input_filename = 'file1.txt'
output_filename = 'file2.txt'
filter_comments(input_filename, output_filename)

# Display data of file2
with open(output_filename, 'r') as f:
    print(f.read())

Write a python program to accept string/sentence from user till the user enters “END”. Each string/sentence entered by user should be a newline in file. Save all the lines in file and display only those lines which begin with capital letter.

Example:
Enter Something (for quit enter END):Hi Friends
Enter Something (for quit enter END):how are you all
Enter Something (for quit enter END):I am fine
Enter Something (for quit enter END):hope you all are fine
Enter Something (for quit enter END):END
The Line started with Capital Letters:
Hi Friends
I am fine"

filename = 'user_lines.txt'

with open(filename, 'w') as file:
    while True:
        user_input = input("Enter Something (for quit enter END): ")
        if user_input.upper() == 'END':
            break
        file.write(user_input + '\n')

with open(filename, 'r') as file:
    lines = file.readlines()
    capital_lines = [line.strip() for line in lines if line[0].isupper()]

print("The Line started with Capital Letters:")
print('\n'.join(capital_lines))

Write a program to compare two text files. If they are different, give the line and column numbers in the files where the first difference occurs.

Example:
File 1: python1.txt
Friends are crazy, Friends are naughty !
Friends are honest, Friends are  best !
Friends are like keygen, friends are like license key !
new We are nothing without friends, Life is not possible without friends !
File 2: python2.txt   
Friends are crazy, Friends are naughty !
Friends 6re honest, Friends are  best !
Friends are like keygen, friends are like license key !
new We are nothing without friends, Life is not possible without friends !    
Output:
line number 2 colNo. 9"

def compare_files(file1, file2):
    with open(file1, 'r') as f1, open(file2, 'r') as f2:
        line_num = 1
        while True:
            line1 = f1.readline()
            line2 = f2.readline()

            if not line1 and not line2:
                break

            col_num = 1
            for char1, char2 in zip(line1, line2):
                if char1 != char2:
                    print(f"Difference at line number {line_num}, colNo. {col_num}")
                    return
                col_num += 1

            if len(line1) != len(line2):
                print(f"Difference at line number {line_num}, colNo. {col_num}")
                return

            line_num += 1

# Example usage:
file1 = 'python1.txt'
file2 = 'python2.txt'
compare_files(file1, file2)

Write a Python program to count the frequency of words in a file

Example: File 1: python1.txt Friends are crazy, Friends are naughty ! Friends are honest, Friends are best ! Friends are like keygen, friends are like license key ! new We are nothing without friends, Life is not possible without friends ! Output: Friends - 5,are - 7,crazy, - 1,naughty - 1,! - 4,honest, - 1,best - 1,like - 2,keygen, - 1,friends - 2,license - 1,key - 1,new - 1,We - 1,nothing - 1,without - 2,friends, - 1,Life - 1,is - 1,not - 1,possible - 1,”

def count_word_frequency(filename):
    with open(filename, 'r') as file:
        words = file.read().split()

    word_frequency = {}
    for word in words:
        if word in word_frequency:
            word_frequency[word] += 1
        else:
            word_frequency[word] = 1

    for word, count in word_frequency.items():
        print(f'{word} - {count}')

# Example usage:
filename = 'python1.txt'
count_word_frequency(filename)

UNIT 7

# string_functions.py

def reverse_string(s):
    return s[::-1]

def uppercase_string(s):
    return s.upper()

def count_vowels(s):
    vowels = 'aeiouAEIOU'
    return sum(1 for char in s if char in vowels)

# main.py
from string_functions import reverse_string, uppercase_string, count_vowels

user_input = input("Enter a string: ")

reversed_str = reverse_string(user_input)
print(f"Reversed String: {reversed_str}")

uppercase_str = uppercase_string(user_input)
print(f"Uppercase String: {uppercase_str}")

vowel_count = count_vowels(user_input)
print(f"Vowel Count: {vowel_count}")

Write a python program to create a directory and subdirectory. It should print the current working directory path and list of names of files present in the given directory.

import os

directory_path = 'example_directory'
subdirectory_path = os.path.join(directory_path, 'example_subdirectory')

os.makedirs(subdirectory_path)

print(f"Current Working Directory: {os.getcwd()}")
print(f"List of Files in Directory: {os.listdir(directory_path)}")

# cal.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b != 0:
        return a / b
    else:
        return "Cannot divide by zero"

# main.py
from cal import add, subtract, multiply, divide

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

result_add = add(num1, num2)
print(f"Addition: {result_add}")

result_subtract = subtract(num1, num2)
print(f"Subtraction: {result_subtract}")

result_multiply = multiply(num1, num2)
print(f"Multiplication: {result_multiply}")

result_divide = divide(num1, num2)
print(f"Division: {result_divide}")

“Write a program to create a module ‘first_word.py’, which returns the first word of any string passed. Show the working of the module, by calling the module with any suitable example.

Input: ‘This is Python Programming’
Output: ‘This’"
# first_word.py

def get_first_word(s):
    return s.split()[0]

# main.py
from first_word import get_first_word

input_string = 'This is Python Programming'
result = get_first_word(input_string)
print(f"Output: {result}")

“Write a python program to copy content of File1 into File2 in which all lines of a file1 or remaining portion of line except those that have hash sign (#) (means comments).

Input:

# Hello LJ
Wish you happy Republic #Day
Happy 74th Republic Day
What a #Parade at Kartavya Path
Very Happy after watching that parade

Output:

Wish you happy Republic 
Happy 74th Republic Day
What a 
Very Happy after watching that parade
"

# main.py

input_filename = 'File1.txt'
output_filename = 'File2.txt'

with open(input_filename, 'r') as input_file, open(output_filename, 'w') as output_file:
    for line in input_file:
        if '#' not in line:
            output_file.write(line)

UNIT 8

Create a class called NumberSet that accepts 2 integers as input, and defines two instance variables: num1 and num2, which hold each of the input integers. Then, create an instance of NumberSet where its num1 is 6 and its num2 is 10. Save this instance to a variable t

class NumberSet:
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

# Create an instance
t = NumberSet(6, 10)

Create a class called Animal that accepts two numbers as inputs and assigns them respectively to two instance variables: arms and legs. Create an instance method called limbs that, when called, returns the total number of limbs the animal has. To the variable name spider, assign an instance of Animal that has 4 arms and 4 legs. Call the limbs method on the spider instance and save the result to the variable name spidlimbs

class Animal:
    def __init__(self, arms, legs):
        self.arms = arms
        self.legs = legs

    def limbs(self):
        return self.arms + self.legs

# Create an instance
spider = Animal(4, 4)

# Call the limbs method
spidlimbs = spider.limbs()

Write a Python program to create a Vehicle class with max_speed and mileage instance attributes.

class Vehicle:
    def __init__(self, max_speed, mileage):
        self.max_speed = max_speed
        self.mileage = mileage

Write a Python class named Student with two attributes student_name, marks. Modify the attribute values of the said class and print the original and modified values of the said attributes.

class Student:
    def __init__(self, student_name, marks):
        self.student_name = student_name
        self.marks = marks

# Create an instance
student_instance = Student("John", 85)

# Print original values
print(f"Original values: {student_instance.student_name}, {student_instance.marks}")

# Modify attribute values
student_instance.student_name = "Jane"
student_instance.marks = 90

# Print modified values
print(f"Modified values: {student_instance.student_name}, {student_instance.marks}")
Original values: John, 85
Modified values: Jane, 90

Write a Python class named Student with two attributes student_id, student_name. Add a new attribute student_class. Create a function to display the entire attribute and their values in Student class.

class Student:
    def __init__(self, student_id, student_name):
        self.student_id = student_id
        self.student_name = student_name
        self.student_class = None

    def display_attributes(self):
        print(f"ID: {self.student_id}, Name: {self.student_name}, Class: {self.student_class}")

# Create an instance
student_instance = Student(1, "John")

# Set the student_class attribute
student_instance.student_class = "Grade 10"

# Display attributes
student_instance.display_attributes()
ID: 1, Name: John, Class: Grade 10

Write a Python class named Rectangle constructed by a length and width and a method which will compute the area of a rectangle.

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

# Create an instance
rectangle_instance = Rectangle(5, 8)

# Compute the area
area = rectangle_instance.area()
print(f"Area of the rectangle: {area}")
Area of the rectangle: 40

Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle.

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * (self.radius ** 2)

    def perimeter(self):
        return 2 * math.pi * self.radius

# Create an instance
circle_instance = Circle(4)

# Compute area and perimeter
area = circle_instance.area()
perimeter = circle_instance.perimeter()

print(f"Area of the circle: {area}")
print(f"Perimeter of the circle: {perimeter}")
Area of the circle: 50.26548245743669
Perimeter of the circle: 25.132741228718345

Write a python program to demonstrate the use of try-except-else in Exception handling

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input! Please enter a number.")
else:
    print(f"The result is: {result}")
Enter a number: 0
Cannot divide by zero!

Write a python program to demonstrate the use of raise in Exception handling

def check_positive_number(num):
    if num <= 0:
        raise ValueError("Number must be positive")

try:
    user_input = int(input("Enter a positive number: "))
    check_positive_number(user_input)
    print("Valid input!")
except ValueError as e:
    print(f"Error: {e}")
Enter a positive number: -3
Error: Number must be positive

Write a python program to demonstrate the use of custom exceptions in Exception handling.

class CustomException(Exception):
    pass

def check_even_number(num):
    if num % 2 != 0:
        raise CustomException("Number must be even")

try:
    user_input = int(input("Enter an even number: "))
    check_even_number(user_input)
    print("Valid input!")
except CustomException as ce:
    print(f"Error: {ce}")
Enter an even number: 3
Error: Number must be even

Write a program to build a simple Student Management System using Object Oriented Programming in Python which can perform the following operations:

accept-This method takes details from the user like name, roll number, and marks for two different subjects. 
display-This method displays the details of every student.
search-This method searches for a particular student from the list of students. This method will ask the user for roll number and then search according to the roll number
delete-This method deletes the record of a particular student with a matching roll number.
update-This method updates the roll number of the student. This method will ask for the old roll number and new roll number. It will replace the old roll number with a new roll number.
The following instructions need to be considered while making a program.
1.  Give class name as Student
2.  Include methods name as accept, display, search, delete and update. (1 mark for each correct method to be formed).
3.  Also form constructor with __init__ () method (2 marks for forming constructor).
4.  2 marks for correct object prepared like after deletion of one roll no of student it should update the list with new roll no. and should display it.
The example is just for understanding but logic should be for any n number of students.
For Example:
List of Students
Name   :  A
RollNo :  1
Marks1 :  100
Marks2 :  100
Name   :  B
RollNo :  2
Marks1 :  90
Marks2 :  90

class Student:
    def __init__(self):
        self.students = []

    def accept(self):
        name = input("Enter student name: ")
        roll_no = int(input("Enter roll number: "))
        marks1 = int(input("Enter marks for subject 1: "))
        marks2 = int(input("Enter marks for subject 2: "))
        student_data = {"Name": name, "RollNo": roll_no, "Marks1": marks1, "Marks2": marks2}
        self.students.append(student_data)
        print("Student details accepted successfully!")

    def display(self):
        print("\nList of Students:")
        for student in self.students:
            print(f"Name   : {student['Name']}")
            print(f"RollNo : {student['RollNo']}")
            print(f"Marks1 : {student['Marks1']}")
            print(f"Marks2 : {student['Marks2']}\n")

    def search(self, roll_no):
        for student in self.students:
            if student['RollNo'] == roll_no:
                print("Student found:")
                print(f"Name   : {student['Name']}")
                print(f"RollNo : {student['RollNo']}")
                print(f"Marks1 : {student['Marks1']}")
                print(f"Marks2 : {student['Marks2']}")
                return
        print("Student not found.")

    def delete(self, roll_no):
        for student in self.students:
            if student['RollNo'] == roll_no:
                self.students.remove(student)
                print("Student deleted successfully.")
                return
        print("Student not found.")

    def update(self, old_roll_no, new_roll_no):
        for student in self.students:
            if student['RollNo'] == old_roll_no:
                student['RollNo'] = new_roll_no
                print("Student roll number updated successfully.")
                return
        print("Student not found.")

# Example usage:
student_system = Student()

# Accepting students
student_system.accept()
student_system.accept()

# Displaying students
student_system.display()

# Searching for a student
student_system.search(1)

# Deleting a student
student_system.delete(1)

# Updating a student's roll number
student_system.update(2, 3)

# Displaying updated list
student_system.display()
Enter student name: rohan
Enter roll number: 12
Enter marks for subject 1: 10
Enter marks for subject 2: 20
Student details accepted successfully!
Enter student name: rohan
Enter roll number: 13
Enter marks for subject 1: 30
Enter marks for subject 2: 40
Student details accepted successfully!

List of Students:
Name   : rohan
RollNo : 12
Marks1 : 10
Marks2 : 20

Name   : rohan
RollNo : 13
Marks1 : 30
Marks2 : 40

Student not found.
Student not found.
Student not found.

List of Students:
Name   : rohan
RollNo : 12
Marks1 : 10
Marks2 : 20

Name   : rohan
RollNo : 13
Marks1 : 30
Marks2 : 40

You own a pizzeria named Olly’s Pizzas and want to create a Python program to handle the customers and revenue. Create the following classes with the following methods:

Class Pizza containing
1.  init method: to initialize the size (small, medium, large), toppings (corn, tomato, onion, capsicum, mushroom, olives, broccoli), cheese (mozzarella, feta, cheddar). Note: One pizza can have only one size but many toppings and cheese. (1.5 marks)
Throw custom exceptions if the selects toppings or cheese not available in lists given above. (1 mark)
2.  price method: to calculate the prize of the pizza in the following way:
small = 50, medium = 100, large = 200
Each topping costs 20 rupees extra, except broccoli, olives and mushroom, which are exotic and so cost 50 rupees each.
Each type of cheese costs an extra 50 rupees. (1.5 marks)
 Class Order containing
1.  init method: to initialize the name, customerid of the customer who placed the order (0.5 marks)
2.  order method: to allow the customer to select pizzas with choice of toppings and cheese (1 mark)
3.  bill method: to generate details about each pizza ordered by the customer and the total cost of the order. (2 marks)

*Note: A customer can get multiple pizzas in one order.

class InvalidToppingException(Exception):
    pass

class InvalidCheeseException(Exception):
    pass

class Pizza:
    def __init__(self, size, toppings, cheese):
        self.size = size
        self.toppings = toppings
        self.cheese = cheese
        self.validate_toppings()
        self.validate_cheese()

    def validate_toppings(self):
        valid_toppings = ['corn', 'tomato', 'onion', 'capsicum', 'mushroom', 'olives', 'broccoli']
        for topping in self.toppings:
            if topping not in valid_toppings:
                raise InvalidToppingException(f"Invalid topping: {topping}")

    def validate_cheese(self):
        valid_cheese = ['mozzarella', 'feta', 'cheddar']
        for cheese in self.cheese:
            if cheese not in valid_cheese:
                raise InvalidCheeseException(f"Invalid cheese: {cheese}")

    def price(self):
        size_price = {'small': 50, 'medium': 100, 'large': 200}
        topping_price = 20
        exotic_toppings_price = 50
        cheese_price = 50

        total_price = size_price[self.size]

        for topping in self.toppings:
            if topping in ['broccoli', 'olives', 'mushroom']:
                total_price += exotic_toppings_price
            else:
                total_price += topping_price

        total_price += len(self.cheese) * cheese_price
        return total_price


class Order:
    def __init__(self, name, customer_id):
        self.name = name
        self.customer_id = customer_id
        self.pizzas = []

    def order(self, pizza):
        self.pizzas.append(pizza)

    def bill(self):
        total_cost = 0
        print(f"Order details for customer {self.name} (ID: {self.customer_id}):")
        for index, pizza in enumerate(self.pizzas, start=1):
            print(f"\nPizza {index}:")
            print(f"Size: {pizza.size}")
            print(f"Toppings: {', '.join(pizza.toppings)}")
            print(f"Cheese: {', '.join(pizza.cheese)}")
            pizza_cost = pizza.price()
            print(f"Cost: {pizza_cost} rupees")
            total_cost += pizza_cost
        print(f"\nTotal Order Cost: {total_cost} rupees")


# Example usage:
try:
    pizza1 = Pizza('medium', ['corn', 'tomato'], ['mozzarella', 'feta'])
    pizza2 = Pizza('large', ['mushroom', 'olives'], ['cheddar'])
    pizza3 = Pizza('small', ['onion', 'capsicum', 'broccoli'], ['mozzarella'])

    order = Order("John Doe", 123)
    order.order(pizza1)
    order.order(pizza2)
    order.order(pizza3)

    order.bill()
except InvalidToppingException as ite:
    print(f"Error: {ite}")
except InvalidCheeseException as ice:
    print(f"Error: {ice}")
Order details for customer John Doe (ID: 123):

Pizza 1:
Size: medium
Toppings: corn, tomato
Cheese: mozzarella, feta
Cost: 240 rupees

Pizza 2:
Size: large
Toppings: mushroom, olives
Cheese: cheddar
Cost: 350 rupees

Pizza 3:
Size: small
Toppings: onion, capsicum, broccoli
Cheese: mozzarella
Cost: 190 rupees

Total Order Cost: 780 rupees

Write a class called WordPlay. It should have a constructor that holds a list of words. The user of the class should pass the list of words through constructor, which user wants to use for the class. The class should have following methods:

    words_with_length(length) — returns a list of all the words of length length
    starts_with(char1) — returns a list of all the words that start with char1
    ends_with(char2) — returns a list of all the words that end with char2
    palindromes() — returns a list of all the palindromes in the list
    only(str1) — returns a list of the words that contain only those letters in str1
    avoids(str2) — returns a list of the words that contain none of the letters in str2

Make Required object for WordPlay class and test all the methods.

For Example:

If input list entered by user is: ['apple', 'banana', 'find', 'dictionary', 'set', 'tuple', 'list', 'malayalam', 'nayan', 'grind', 'apricot']

words_with_length (5) should return ['apple', 'tuple', 'nayan', 'grind']
starts_with ('a') should return ['apple', 'apricot']
ends_with ('d') should return ['find', 'grind']
palindromes () should return ['malayalam', 'nayan']
only ('bna') should return ['banana']
avoids ('amkd') should return ['set', 'tuple', 'list'].

class WordPlay:
    def __init__(self, word_list):
        self.words = word_list

    def words_with_length(self, length):
        return [word for word in self.words if len(word) == length]

    def starts_with(self, char1):
        return [word for word in self.words if word[:len(char1)] == char1]

    def ends_with(self, char2):
        return [word for word in self.words if word[-len(char2):] == char2]

    def palindromes(self):
        return [word for word in self.words if word == word[::-1]]

    def only(self, str1):
        return [word for word in self.words if self.all_chars_in_word(str1, word)]

    def avoids(self, str2):
        return [word for word in self.words if not self.any_char_in_word(str2, word)]

    @staticmethod
    def all_chars_in_word(chars, word):
        for char in chars:
            char_found = False
            for w_char in word:
                if w_char == char:
                    char_found = True
                    break
            if not char_found:
                return False
        return True

    @staticmethod
    def any_char_in_word(chars, word):
        for char in chars:
            for w_char in word:
                if w_char == char:
                    return True
        return False

# Example usage:
word_list = ['apple', 'banana', 'find', 'dictionary', 'set', 'tuple', 'list', 'malayalam', 'nayan', 'grind', 'apricot']

word_play = WordPlay(word_list)

print("Words with length 5:", word_play.words_with_length(5))
print("Words starting with 'a':", word_play.starts_with('a'))
print("Words ending with 'd':", word_play.ends_with('d'))
print("Palindromes:", word_play.palindromes())
print("Words containing only 'bna':", word_play.only('bna'))
print("Words avoiding 'amkd':", word_play.avoids('amkd'))
Words with length 5: ['apple', 'tuple', 'nayan', 'grind']
Words starting with 'a': ['apple', 'apricot']
Words ending with 'd': ['find', 'grind']
Palindromes: ['malayalam', 'nayan']
Words containing only 'bna': ['banana']
Words avoiding 'amkd': ['set', 'tuple', 'list']

Write a python program that has class store which keeps record of code and price of each product. Display a menu of all products to the user and prompt him to enter the quantity of each item required. generate a bill and display total amount.

Sample Output:
enter no of items: 3
enter code of item: milk
enter cost of item: 30
enter code of item: apple
enter cost of item: 35
enter code of item: gems
enter cost of item: 40
Item Code    Price
milk          30
apple         35
gems          40
Enter quantity of each item: 
Enter quantity of milk : 2
Enter quantity of apple : 3
Enter quantity of gems : 4

************************Bill**********************
ITEM     PRICE  QUANTITY           SUBTOTAL
milk      30             2       60
apple     35             3       105
gems      40             4       160
**************************************
Total=  325

class Store:
    def __init__(self):
        self.products = {}

    def add_product(self, code, price):
        self.products[code] = price

    def display_menu(self):
        print("Item Code\t Price")
        for code, price in self.products.items():
            print(f"{code}\t\t {price}")

    def generate_bill(self, quantities):
        print("\n************************Bill**********************")
        print("ITEM\t PRICE\t QUANTITY\t\t SUBTOTAL")
        
        total_amount = 0
        for code, quantity in quantities.items():
            if code in self.products:
                price = self.products[code]
                subtotal = price * quantity
                total_amount += subtotal
                print(f"{code}\t {price}\t {quantity}\t\t\t {subtotal}")

        print("**************************************************")
        print(f"Total=  {total_amount}")

# Example usage:
store = Store()

# Adding products to the store
store.add_product("milk", 30)
store.add_product("apple", 35)
store.add_product("gems", 40)

# Displaying the menu
store.display_menu()

# Taking input for quantities
num_items = int(input("Enter no of items: "))
quantities = {}
for _ in range(num_items):
    code = input("Enter code of item: ")
    quantity = int(input(f"Enter quantity of {code} : "))
    quantities[code] = quantity

# Generating and displaying the bill
store.generate_bill(quantities)
Item Code    Price
milk         30
apple        35
gems         40
Enter no of items: 3
Enter code of item: milk
Enter quantity of milk : 2
Enter code of item: apple
Enter quantity of apple : 3
Enter code of item: gems
Enter quantity of gems : 4

************************Bill**********************
ITEM     PRICE   QUANTITY        SUBTOTAL
milk     30  2           60
apple    35  3           105
gems     40  4           160
**************************************************
Total=  325

Write a python program that has a class Point with attributes as the x and y co-ordinates.

1.  Add a method ‘distance from origin’ to class Point which returns the distance of the given point from origin. The equation is 

2.  Add a method ‘translate’ to class Point, which returns a new position of point after translation
3.  Add a method ‘reflect_x’ to class Point, which returns a new point which is the reflection of the point about the x-axis. 
4.  Add a method ‘distance’ to return distance of the given point with respect to the other point. The formula for calculating distance between A(x1,y1) and B(x2,y2) is 


After creating class blueprint run the following test case - 

Test Case –                           Point (1,2)
Distance from origin -          2.23
Translate method -              point (1,2) translated by (1,1) increment will be at (2,3) now
Reflect_x Method -              Point (2,3) after given reflection will be at  (2,-3)
Distance Method -                distance between point (2,-3) and (3,4) is 1.41  

import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def distance_from_origin(self):
        return math.sqrt(self.x**2 + self.y**2)

    def translate(self, dx, dy):
        return Point(self.x + dx, self.y + dy)

    def reflect_x(self):
        return Point(self.x, -self.y)

    def distance(self, other_point):
        return math.sqrt((self.x - other_point.x)**2 + (self.y - other_point.y)**2)

# Test Case
point = Point(1, 2)

# Distance from origin
print(f"Distance from origin: {point.distance_from_origin():.2f}")

# Translate method
translated_point = point.translate(1, 1)
print(f"Translate method: Point ({point.x},{point.y}) translated by (1,1) is at ({translated_point.x},{translated_point.y}) now")

# Reflect_x method
reflected_point = point.reflect_x()
print(f"Reflect_x method: Point ({point.x},{point.y}) after given reflection is at ({reflected_point.x},{reflected_point.y})")

# Distance method
other_point = Point(3, 4)
print(f"Distance method: Distance between Point ({point.x},{point.y}) and ({other_point.x},{other_point.y}) is {point.distance(other_point):.2f}")
Distance from origin: 2.24
Translate method: Point (1,2) translated by (1,1) is at (2,3) now
Reflect_x method: Point (1,2) after given reflection is at (1,-2)
Distance method: Distance between Point (1,2) and (3,4) is 2.83

A possible collection of classes which can be used to represent a music collection (for example, inside a music player), focusing on how they would be related by composition. You should include classes for songs, artists, albums and playlists. For simplicity you can assume that any song or album has a single “artist” value (which could represent more than one person), but you should include compilation albums (which contain songs by a selection of different artists). The “artist” of a compilation album can be a special value like “Various Artists”. You can also assume that each song is associated with a single album, but that multiple copies of the same song (which are included in different albums) can exist.Write a simple implementation of this model which clearly shows how the different classes are composed. Write some example code to show how you would use your classes to create an album and add all its songs to a playlist. Class Album should have a method to add track, class Artist should have methods to add album and add song, class Playlist should also have a method to add song.{.smaller}

class Song:
    def __init__(self, title, duration):
        self.title = title
        self.duration = duration
        self.album = None  # Associated album

class Artist:
    def __init__(self, name):
        self.name = name
        self.albums = []  # List of albums by the artist
        self.songs = []   # List of individual songs by the artist

    def add_album(self, album):
        self.albums.append(album)

    def add_song(self, song):
        self.songs.append(song)

class Album:
    def __init__(self, title, artist):
        self.title = title
        self.artist = artist
        self.tracks = []  # List of tracks in the album

    def add_track(self, song):
        self.tracks.append(song)
        song.album = self  # Set the associated album for the song

class Playlist:
    def __init__(self, title):
        self.title = title
        self.songs = []  # List of songs in the playlist

    def add_song(self, song):
        self.songs.append(song)

# Example usage:
# Create artists
artist1 = Artist("Artist1")
artist2 = Artist("Various Artists")

# Create songs
song1 = Song("Song1", 180)
song2 = Song("Song2", 200)

# Create albums
album1 = Album("Album1", artist1)
album1.add_track(song1)
album1.add_track(song2)

album2 = Album("Compilation Album", artist2)
album2.add_track(song1)

# Add albums to artists
artist1.add_album(album1)
artist2.add_album(album2)

# Create a playlist
playlist = Playlist("My Playlist")

# Add songs to the playlist
playlist.add_song(song1)
playlist.add_song(song2)

# Display information
print("Playlist:", playlist.title)
print("Songs in the playlist:")
for song in playlist.songs:
    print(f"- {song.title} ({song.duration} seconds)")

# Display artists and their albums
print("\nArtists and their albums:")
for artist in [artist1, artist2]:
    print(f"{artist.name}:")
    for album in artist.albums:
        print(f"- {album.title}")

# Display albums and their tracks
print("\nAlbums and their tracks:")
for album in [album1, album2]:
    print(f"{album.title} by {album.artist.name}:")
    for track in album.tracks:
        print(f"- {track.title} ({track.duration} seconds)")

Stacks and Queues. Write a class SQ that defines a data structure that can behave as both a queue (FIFO) or a stack (LIFO), There are five methods that should be implemented:

1.  make a constructor with a valid parameter  
2.  shift() returns the first element and removes it from the list. Also, use the custom(raise) exception in this method.
3.  unshift() "pushes" a new element to the front or head of the list
4.  push() adds a new element to the end of a list
5.  pop() returns the last element and removes it from the list
6.  remove() returns the maximum element of the list and removes it from the list.
7.  Create the object and call all methods of the SQ class.

class EmptyListError(Exception):
    pass

class SQ:
    def __init__(self, initial_list=None):
        self.items = initial_list or []

    def shift(self):
        if not self.items:
            raise EmptyListError("Cannot shift from an empty list")
        return self.items.pop(0)

    def unshift(self, item):
        self.items.insert(0, item)

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.items:
            raise EmptyListError("Cannot pop from an empty list")
        return self.items.pop()

    def remove(self):
        if not self.items:
            raise EmptyListError("Cannot remove from an empty list")
        max_element = max(self.items)
        self.items.remove(max_element)
        return max_element

    def __str__(self):
        return str(self.items).replace("[0, ", "[")

# Example usage:
sq = SQ([1, 2, 3, 4, 5])

# Shift
try:
    print("Shifted:", sq.shift())
except EmptyListError as e:
    print(e)

# Unshift
sq.unshift(0)
print("After Unshift:", sq)

# Push
sq.push(6)
print("After Push:", sq)

# Pop
try:
    print("Popped:", sq.pop())
except EmptyListError as e:
    print(e)

# Remove
try:
    print("Removed Max Element:", sq.remove())
except EmptyListError as e:
    print(e)

# Display final state
print("Final State:", sq)
Shifted: 1
After Unshift: [2, 3, 4, 5]
After Push: [2, 3, 4, 5, 6]
Popped: 6
Removed Max Element: 5
Final State: [2, 3, 4]